package com.fauks.restful.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 *     author : fauks
 *     e-mail : xiaofauks@163.com
 *     time   : 2019/8/23
 *     desc   : Gson工具类
 *     version: 1.0
 * </pre>
 */
public class EasyGsonUtils {

    private static final String DATEFORMAT_default = "yyyy-MM-dd HH:mm:ss";

    /**
     * 使用默认的gson配置进行反序列化
     */
    public static <T> T fromJsonDefault(String json, TypeToken<T> typeToken) {
        Gson gson = new Gson();
        return gson.fromJson(json, typeToken.getType());
    }

    public static <T> T fromJson(String json, TypeToken<T> typeToken) {
        return fromJson(json, typeToken.getType());
    }

    public static <T> T fromJson(JsonReader json, Type typeToken) {
        return getCustomGson().fromJson(json, typeToken);
    }

    public static <T> T fromJson(Reader json, Class<T> typeToken) {
        return getCustomGson().fromJson(json, typeToken);
    }

    public static <T> T fromJson(Reader json, Type typeToken) {
        return getCustomGson().fromJson(json, typeToken);
    }

    public static String toJson(Object obj, boolean format) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        //设置默认时间格式
        gsonBuilder.setDateFormat(DATEFORMAT_default);
        //添加格式化设置
        if (format) {
            gsonBuilder.setPrettyPrinting();
        }
        Gson gson = gsonBuilder.create();
        return gson.toJson(obj);
    }

    public static String toJson(Object obj, Type type) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        //设置默认时间格式
        gsonBuilder.setDateFormat(DATEFORMAT_default);
        //添加格式化设置
        Gson gson = gsonBuilder.create();
        return gson.toJson(obj, type);
    }

    private static <T> T fromJson(String json, Type typeToken) {
        Gson gson = getCustomGson();
        return gson.fromJson(json, typeToken);
    }

    //自定义Gson配置
    private static Gson getCustomGson() {
        return new GsonBuilder()
                .setDateFormat(DATEFORMAT_default)
                // 重写map的反序列化
                .registerTypeAdapter(new TypeToken<Map<String, Object>>() {
                }.getType(), new MapTypeAdapter()).create();
    }

    /**
     * Gson map映射
     */
    public static class MapTypeAdapter extends TypeAdapter<Object> {

        @Override
        public Object read(JsonReader in) throws IOException {
            JsonToken token = in.peek();
            switch (token) {
                case BEGIN_ARRAY:
                    List<Object> list = new ArrayList<Object>();
                    in.beginArray();
                    while (in.hasNext()) {
                        list.add(read(in));
                    }
                    in.endArray();
                    return list;
                case BEGIN_OBJECT:
                    Map<String, Object> map = new LinkedTreeMap<String, Object>();
                    in.beginObject();
                    while (in.hasNext()) {
                        map.put(in.nextName(), read(in));
                    }
                    in.endObject();
                    return map;
                case STRING:
                    return in.nextString();
                case NUMBER:
                    // 改写数字的处理逻辑，将数字值分为整型与浮点型。
                    double dbNum = in.nextDouble();
                    // 数字超过long的最大值，返回浮点类型
                    if (dbNum > Long.MAX_VALUE) {
                        return dbNum;
                    }
                    // 判断数字是否为整数值
                    long lngNum = (long) dbNum;
                    if (dbNum == lngNum) {
                        return lngNum;
                    } else {
                        return dbNum;
                    }
                case BOOLEAN:
                    return in.nextBoolean();
                case NULL:
                    in.nextNull();
                    return null;
                default:
                    throw new IllegalStateException();
            }
        }

        @Override
        public void write(JsonWriter out, Object value) throws IOException {
            // 序列化无需实现
        }
    }
}